package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.PermissionDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.Permission;
import com.itheima.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = PermissionService.class)
@Transactional
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    PermissionDao permissionDao;


    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        //之前：业务逻辑1.查询总记录数  2.查询当前页面显示数据
        //1.设置分页参数
        PageHelper.startPage(currentPage,pageSize);
        //2.需要分页的语句
        Page<Permission> permissionPage = permissionDao.selectByCondition(queryString);
        return new PageResult(permissionPage.getTotal(),permissionPage.getResult());
    }

    @Override
    public void add(Permission permission) {
        permissionDao.add(permission);
    }

    @Override
    public void deleteById(Integer id) {
        //1.根据检查项id 到t_role_permission查询关系是否存在
        int count = permissionDao.findCountByPermissionId(id);
        //2.存在 抛出异常 当前检查和下和检查组已经关联，无法删除
        if(count > 0){
            throw new RuntimeException(MessageConstant.DELETE_PERMISSION_ROLE_FAIL);
        }
        //3.不存在 直接删除
        permissionDao.deleteById(id);
    }

    @Override
    public Permission findById(Integer id) {
        return permissionDao.findById(id);
    }

    @Override
    public void edit(Permission permission) {
        permissionDao.edit(permission);
    }

    /**
     * 查询所有权限列表
     * @return
     */
    @Override
    public List<Permission> findAll() {
        return permissionDao.findAll();
    }

}
